<template>
  <!-- 消息列表 -->
  <div class="messageListOuter">
    <ul v-if="state.msgList" v-for="item in state.msgList" :key="item.id">
      <li>
        <p><span class="point">·</span>{{item.userName}}-{{item.dateTime}}</p>
        <p>{{item.msg}}</p>
      </li>
    </ul>
    <div v-else class="msgNull">
      <h2>数据为空</h2>
    </div>
  </div>

  <!-- 聊天输入框 -->
  <div class="sendMessageOuter">
    <input type="text" class="messageInp" v-model="state.msg" placeholder="请输入信息">
    <button class="sendMessage" @click="sendMessage">发送</button>
  </div>
  <div class="footer">
    <button class="outLog" @click="outLog">退出</button>
  </div>
</template>
 
<script setup lang='ts'>
import { onMounted, reactive } from 'vue';
import { useRouter } from 'vue-router';

import useWebsocket from '../hooks/websocket'

const router = useRouter()

interface msgListI {
  id: string,
  userName: string,
  dateTime: number,
  msg: string
}

interface stateI {
  msg: string,
  msgList: Array<msgListI>
}

const state = reactive<stateI>({
  msg: '',
  msgList: []
})

let userName: string = ''

onMounted(() => {
  userName = localStorage.getItem('token')!
})

const ws = useWebsocket((e: any) => {

  const reader = new FileReader();
  reader.readAsText(e.data, "UTF-8");
  reader.onload = () => {
    //字符串和json格式
    const result = JSON.parse(reader.result as string);
    state.msgList.push(result)
  }
})

// 发送
const sendMessage = () => {
  if (state.msg.trim() === '') {
    return alert('请输入信息')
  }

  // state.msgList.push()

  // 发送到服务器
  ws.send(JSON.stringify({
    id: '' + state.msgList.length + 1 as string,
    userName,
    dateTime: new Date().getTime(),
    msg: state.msg
  }))

  state.msg = ''
}

// 退出
const outLog = () => {
  const res: Boolean = confirm('确定退出')
  if (res) {
    localStorage.removeItem('token')
    state.msgList = []
    router.push('/login')
  }

}

</script>
 
<style lang='scss' scoped>
.messageListOuter {
  margin-top: 10px;
  margin-bottom: 10px;
  font-size: 12px;

  li {
    &:last-child {
      margin-bottom: 10px;
    }

    p {
      display: flex;
      align-items: center;

      &:last-child {
        font-size: 14px;
        margin-left: 20px;
      }

      .point {
        display: inline-block;
        font-size: 30px;
        margin-right: 10px;
      }
    }
  }


  .msgNull {
    margin-left: 20px;
  }
}

.messageListOuter,
.sendMessageOuter {
  padding: 0 10px;

  .messageInp {
    height: 30px;
    margin-right: 10px;
    padding-left: 10px;
  }

  .sendMessage {
    height: 30px;
    padding: 0 10px;
  }
}

.footer {
  margin-top: 30px;

  .outLog {
    height: 30px;
    padding: 0 10px;
    margin-left: 60px;
  }
}
</style>